package com.jumper.study.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import com.jumper.study.admin.dto.req.LessonCategoryReq;
import com.jumper.study.admin.dto.resp.LessonCategoryResp;
import com.jumper.study.admin.service.LessonCategoryService;
import com.jumper.study.admin.service.LessonService;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.db.model.LessonCategory;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;


@RestController
@RequestMapping("/api/backend/category")
public class LessonCategoryController {

    @Autowired
    private LessonCategoryService categoryService;

    @Autowired
    private LessonService lessonService;

    @GetMapping("")
    public CommonResult<List<LessonCategoryResp>> getList() {
        List<LessonCategory> categories = categoryService.list();

        return CommonResult.success(formatList(categories));
    }

    private List<LessonCategoryResp> formatList(List<LessonCategory> categories) {
        Map<Integer, LessonCategoryResp> respList = new HashMap<>();
        for(LessonCategory category : categories) {
            if (category.getParentId() == 0) {
                respList.put(category.getId(), new LessonCategoryResp(category.getId(), category.getTitle(), category.getParentId(), category.getSort()));
            } else {
                respList.get(category.getParentId()).addChild(new LessonCategoryResp(category.getId(), category.getTitle(), category.getParentId(), category.getSort()));
            }
        }
        return respList.values().stream().toList();
    }

    @GetMapping("/{id}")
    public CommonResult<LessonCategoryResp> getItem(@PathVariable Integer id) {
        LessonCategory category = categoryService.getById(id);
        if (category == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }

        return CommonResult.success(new LessonCategoryResp(category.getId(), category.getTitle(), category.getParentId(), category.getSort()));
    }

    @PostMapping("/")
    public CommonResult<Boolean> create(@RequestBody @Validated LessonCategoryReq req) {
        LessonCategory category = new LessonCategory();
        category.setTitle(req.getTitle());
        category.setParentId(req.getParentId());
        category.setSort(req.getSort());
        boolean result = categoryService.save(category);

        return CommonResult.success(result);
    }

    @PostMapping("/{id}")
    public CommonResult<Boolean> update(@PathVariable Integer id, @RequestBody @Validated LessonCategoryReq req) {
        LessonCategory category = categoryService.getById(id);
        if (category == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        category.setTitle(req.getTitle());
        category.setSort(req.getSort());
        boolean result = categoryService.updateById(category);

        return CommonResult.success(result);
    }
    
    @DeleteMapping("/{id}")
    public CommonResult<Boolean> delete(@PathVariable Integer id) {
        LessonCategory category = categoryService.getById(id);
        if (category == null) {
            return CommonResult.success(true);
        }
        if (categoryService.hasChild(id)) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "不能删除有子分类的分类");
        }
        if (lessonService.hasLessons(id)) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getCode(), "不能删除有课程的分类");
        }

        boolean result = categoryService.removeById(category);

        return CommonResult.success(result);
    }
}
